package com.powernode.settings.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.powernode.commons.utils.ResponseData;
import com.powernode.commons.utils.UUIDUtils;
import com.powernode.settings.bean.DicValueBean;
import com.powernode.settings.dao.DicValueMapper;
import com.powernode.settings.service.DicTypeService;
import com.powernode.settings.service.DicValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DicValueServiceImpl implements DicValueService {
    @Autowired
    private DicValueMapper dao;

    /**
     * 分页查询字典值
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public ResponseData findAll(Integer pageNum, Integer pageSize,String code) {
        Page<DicValueBean> page = PageHelper.startPage(pageNum, pageSize);
        dao.selectAll(code);
        return ResponseData.ok(page.getResult(),page.getTotal());
    }

    /**
     * 添加
     * 注意:相同类型下的字典值不能重复,且字典值能不能为空
     * @param val
     * @return
     */
    @Override
    public ResponseData add(DicValueBean val) {
        DicValueBean dicValue = dao.selectByTypeCodeAndValue(val.getTypeCode(), val.getValue());
        if (null!=dicValue){
            return  ResponseData.error("该字典类型下已有该字典值");
        }
        if (StrUtil.isEmpty(val.getValue())){
            return ResponseData.error("字典值不能为空");
        }
        //设置主键
        val.setId(UUIDUtils.getUUID());
        int row = dao.insertSelective(val);
        if (row>0){
            return ResponseData.ok();
        }
        return ResponseData.error();
    }

    /**
     * 修改字典值
     * @param val
     * @return
     */
    @Override
    public ResponseData modify(DicValueBean val) {
        //表中的原始数据
        DicValueBean oldVal = dao.selectByPrimaryKey(val.getId());
        //字典值修改了
        if (!StrUtil.equals(oldVal.getValue(),val.getValue())){
            //根据字典类型和字典查询
            DicValueBean dicValue = dao.selectByTypeCodeAndValue(val.getTypeCode(), val.getValue());
            if (null!=dicValue){
                return ResponseData.error("该字典类型下已有该字典值");
            }
        }
        int row = dao.updateByPrimaryKeySelective(val);
        if (row>0){
            return ResponseData.ok();
        }
        return ResponseData.error();
    }

    /**
     * 批量或单个删除
     * @param ids
     * @return
     */
    @Override
    public ResponseData removeBatch(String ids) {
        String[] idArr = ids.split(",");
        int row = dao.delBatch(idArr);
        if (row>0){
            return ResponseData.ok();
        }
        return ResponseData.error();
    }

    /**
     * 根据字典类型查询字典值
     * @param code
     * @return
     */
    @Override
    public ResponseData findByCode(String code) {
        return ResponseData.ok(dao.selectByCode(code));
    }
}
